package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.HeaderImgDao;
import com.zhiyun.hxzy.domain.HeaderImg;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.chrono.HijrahEra;
import java.util.UUID;

@Service
@Transactional
public class HeaderImgService {
    @Autowired
    private HeaderImgDao headerImgDao;
    @Autowired
    private UploadUtil uploadUtil;

    public Page<HeaderImg> findAll(int pageNum, int pageSize){
        if(pageNum<0){
            pageNum=0;
        }
        Pageable pageable= PageRequest.of (pageNum,pageSize, Sort.by(Sort.Direction.DESC, "id"));
        Page<HeaderImg> headerImgs = headerImgDao.findAll (pageable);
        return headerImgs;
    }
    public void addHeaderImg(HeaderImg headerImg){
        headerImgDao.save (headerImg);
    }

    public void deleteHeaderImg(Long[] ids){
        if (ids!=null){
            for (Long id:ids){
                HeaderImg headerImg = headerImgDao.getOne (id);
                headerImgDao.delete (headerImg);
            }
        }
    }

    public void updateHeaderImg(Long[] ids){
        for (Long id:ids){
            HeaderImg headerImg = headerImgDao.getOne (id);
            if (headerImg.getStatus ()==1){
                headerImg.setStatus (0);
                headerImgDao.save (headerImg);
            }else if (headerImg.getStatus ()==0){
                headerImg.setStatus (1);
                headerImgDao.save (headerImg);
            }
        }
    }


    public Result update(MultipartFile file){
        String path = uploadUtil.upload(file);
        return new Result(path,true);
    }

    public HeaderImg findById(Long id){
        return headerImgDao.findById(id).get();
    }

    public void addorUpdate(HeaderImg headerImg) {
        headerImgDao.save(headerImg);
    }
}
